/*
 * 调用的是本地的map服务器，如果是其他的服务器，需修改
 */
var defaultEventTypeIcon = "/wcsi/img/defaultEventType.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var tempgraphic;
var g_labels = "";
var g_textsearch = "", g_textvalue = "";
var g_value = "", g_left, g_right;
var arcTool, manhole_cover_p;
var hander;
var centerX = 106.638;// 120.206354450751;
var centerY = 26.684;// 30.0725834699399;
var toolbar;
var drawHandler;
var gsvc;// 测量面积
var userLayer;
var text_graphic;
var dynamic;
var gridCenterX = 106.62783532184868;
var gridCenterY = 26.686101063755615;
var interval;
var intervalflashTime;
var intervalflashTimeEvent;
var intervalflashTimeWarning;
var intervalflashTimePart;
var FlickerPointType = "reportFlickerPointType";
var showFlickerPointTyp = FlickerPointType;
var showFlickerEventPointType = "eventFlickerPointType";
var showFlickerWaringPointType = "warningFlickerPointType";
var socketList;
require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct", "esri/tasks/GeometryService" ], function(Map,
		Color, Graphic, InfoTemplate, SpatialReference, HeatmapRenderer,
		OverviewMap, Scalebar, Measurement, Units, TDTLayer, TDTAnnoLayer,
		TDT_ImgLayer, TDT_ImgAnnoLayer, GraphicsLayer,
		ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, FeatureLayer,
		Point, Polyline, Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
		PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
		LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
		domConstruct, GeometryService) {
	$("#map").css({"height":+$("#right").height()+"px"}); 
	map = new Map("map", {
		
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 17,
		minZoom : 15,
		maxZoom : 18
	});
	var vec = new TDTLayer();
	var veca = new TDTAnnoLayer();
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);
	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});
	scalebar.show();
	drawHandler = Draw;
    dynamic = new ArcGISTiledMapServiceLayer(arcGisUrl
			+ "/arcgis/rest/services/ByMap/MapServer");
	dynamic.id = "dynamic";
	map.addLayer(dynamic);

	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	userLayer = new FeatureLayer(url + "/19", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "userLayer"
	});
	map.addLayer(userLayer);

	userLayer.setMaxScale(0);
	userLayer.setMinScale(4508.935440959931);
	
	userLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	userLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});
	

	gsvc = new GeometryService(arcGisUrl
			+ "/arcgis/rest/services/Utilities/Geometry/GeometryServer");

	toolbar = new Draw(map);
	dojo.connect(toolbar, "onDrawEnd", addToMap);
	dojo.connect(userLayer, "onClick", showUserDetail);
});

//网格部门对应人员信息
function showdeptUserDetail(deptId){
	var url = window.rootPath+"/ui/userTrajectoryHistory/getDeptFollowView/"+deptId;
	$('#deptIframe').attr('src',url);
	$('#deptModal').modal('show');
	
};

//人员展示信息
function showUserDetail(evt){
	console.log("userLayer:click")
	if (evt.graphic) {
		console.log("user:click");
		var id = evt.graphic.user.id;
		var isfollow=evt.graphic.isfollow;
		var url = window.rootPath+"/ui/index/getUserView/"+id+"/"+isfollow;
		$('#userIframe').attr('src',url);
		$('#userModal').modal('show');
	}
}

function openModal(type){
	if(type="event"){
		var url = window.rootPath+"/ui/userTrajectoryHistory/getEventFollowView";
		$('#eventIframe').attr('src',url);
		$('#eventModal').modal('show');
	}
}

function addToMap(geometry) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块
	// 判断几何图形的类型
	switch (geometry.type) {
	case "point":
		var symbolurl = getIconForSelectNode();
		var symbol = new esri.symbol.PictureMarkerSymbol({
			"url" : symbolurl, // 图标路径
			"width" : 20, // 图标的宽度
			"height" : 20
		// 图标的高度
		});
		break;
	case "polyline":
		var symbol = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([ 255,
						0, 0 ]), 4);
		break;
	case "polygon":

		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 145, 0, 0.35 ]));
		/*
		 * // 测量面积 require( [ "esri/tasks/AreasAndLengthsParameters" ],
		 * function(AreasAndLengthsParameters) { var areasAndLengthParams = new
		 * AreasAndLengthsParameters(); areasAndLengthParams.lengthUnit =
		 * esri.tasks.GeometryService.UNIT_KILOMETER;
		 * areasAndLengthParams.areaUnit =
		 * esri.tasks.GeometryService.UNIT_SQUARE_KILOMETERS; gsvc.simplify([
		 * geometry ], function(simplifiedGeometries) {
		 * areasAndLengthParams.polygons = simplifiedGeometries;
		 * gsvc.areasAndLengths(areasAndLengthParams); }); });
		 */
		break;
	case "extent":
		/*var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;*/
		var graphics = partLayer.graphics;
		var results = [];
		var ids = "";
		for (var i = 0; i < graphics.length; i++) {
			if (geometry.contains(graphics[i].geometry) && graphics[i].attributes&&graphics[i].attributes.part
					&&graphics[i].attributes.part.partType&&graphics[i].attributes.part.partType.value=="1") {// &&graphics[i].pointType==tvPointType
				results.push(graphics[i].attributes.id);
				ids += graphics[i].attributes.id + ",";
			}
		}
		console.log("TV list:"+ids);
		$("#videoModal").modal("show");
		return;
	case "multipoint":
		var symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 0, 0, 0 ]), 1), new dojo.Color([ 255,
						255, 0, 0.5 ]));
		break;
	}
	var graphic = new esri.Graphic(geometry, symbol);

	map.graphics.add(graphic);
	var data = {};

	if (geometry.type == "polyline" && geometry.paths != undefined) {
		data.longitude = geometry.paths[0][0][0];
		data.latitude = geometry.paths[0][0][1];
		map.graphics.add(createPoint(data, "../img/location_start.png",25,25));

		data.longitude = geometry.paths[0][geometry.paths[0].length - 1][0];
		data.latitude = geometry.paths[0][geometry.paths[0].length - 1][1];
		map.graphics.add(createPoint(data, "../img/location_end.png",25,25));

		var textSymbol = new esri.symbol.TextSymbol("测量长度:");

		var point = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			}
		};

		text_graphic = new esri.Graphic(point);
		text_graphic.setSymbol(textSymbol);
		map.graphics.add(text_graphic);
	}
	if (geometry.type == "polygon" && geometry.rings != undefined) {
		for (var i = 0; i < geometry.rings[0].length; i++) {
			data.longitude = geometry.rings[0][i][0];
			data.latitude = geometry.rings[0][i][1];
			map.graphics.add(createPoint(data, "../img/location_start.png",25,25));
		}
		var textSymbol = new esri.symbol.TextSymbol("测量面积:");
		var point = graphic.geometry.getCentroid();
		text_graphic = new esri.Graphic(point, textSymbol);
		map.graphics.add(text_graphic);

	}
	// map.graphics.add(graphic); // 将绘图加入到图层中

	// 进行投影转换，完成后调用projectComplete

	MeasureGeometry(geometry);

};
//默认线样式
function getLineDefaultSymbol(){
	var symbol = new esri.symbol.SimpleLineSymbol(
			esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([ 255,
			                                                           145, 0 ]), 4);
	return symbol;
}
function getLineHighSymbol(){
	var symbol = new esri.symbol.SimpleLineSymbol(
			esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([ 255,
					0, 0 ]), 4);
	return symbol;
}
//默认网格样式
function getPolygonDefaultSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 145, 0,
					0.35 ]));

	return symbol;
}
//高亮网格样式
function getPolygonHighSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 255, 0,
					0.75 ]));
	return symbol;
}
function clearLayer(){
	userLayer.clear();
	if(intervalflashTime){
		clearInterval(intervalflashTime);
		intervalflashTime=null;
	}
	if(intervalflashTimeEvent){
		clearInterval(intervalflashTimeEvent);
		intervalflashTimeEvent=null;
	}
	if(intervalflashTimePart){
		clearInterval(intervalflashTimePart);
		intervalflashTimePart=null;
	}

	if(intervalflashTimeWarning){
		clearInterval(intervalflashTimeWarning);
		intervalflashTimeWarning=null;
	}
	
	$('#registerEventName').val('');
	$('#registerEventAccTime').val('');
	$('#gridName').val('');
	$('#eventName').val('');
	$('#registerEventSeriousLevelTitle').val('');
	$('#registerEventContent').val('');
	$('#registerEventMemo').val('');
	
	$('#eventInfoDiv').hide();
	$('#userInfoDiv').hide();
}
function setUserFollow(userid,isfollow){
	$('#userModal').modal('hide');
	for(var i=0;i<userLayer.graphics.length;i++){
		if(userLayer.graphics[i].user && userLayer.graphics[i].user.id==userid){
			if(userLayer.graphics[i].geometry.type=="polyline"){
				if(isfollow=="0"){
					userLayer.graphics[i].hide();
				}else if(isfollow=="1"){
					userLayer.graphics[i].show();
				}		
		}
		userLayer.graphics[i].isfollow=isfollow;
		}
	}
};
function getUserToMapIds(list){
	$('#deptModal').modal('hide');
	var ids="";
	for(var i=0;i<list.length;i++){
		ids+=list[i]+",";
	}
	ids=ids.substring(0,ids.length-1);
	var cyc = $('#cyc').val();
	var beginDate = $('#beginDate').val();
	var endDate = $('#endDate').val();
	var d = {
		cyc: cyc,
		beginDate: beginDate,
		endDate : endDate
	}
	$('#ids').val(ids);
	var url=window.rootPath+"/ui/userTrajectoryHistory/getUserListByIds/"+ids;
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "post",
		dataType:"json",
		data : JSON.stringify(d),
		contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
		success:function(data){
			var users = data.users;
			clearLayer();
			$("#search").val('');
			initFollowPerson(users);
			initfollowState();
			$('#userInfoDiv').show();
		}
	});
};
function getUserToMapIds2(){
	var cyc = $('#cyc').val();
	var beginDate = $('#beginDate').val();
	var endDate = $('#endDate').val();
	var d = {
			cyc: cyc,
			beginDate: beginDate,
			endDate : endDate
	}
	var ids = $('#ids').val();
	var url=window.rootPath+"/ui/userTrajectoryHistory/getUserListByIds/"+ids;
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "post",
		dataType:"json",
		data : JSON.stringify(d),
		contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
		success:function(data){
			var users = data.users;
			clearLayer();
			$("#search").val('');
			initFollowPerson(users);
			initfollowState();
			$('#userInfoDiv').show();
		}
	});
};

function getEventToMap(data){
	$('#eventModal').modal('hide');
	
	clearLayer();
	
	if(data){
		$('#registerEventName').val(data.registerEventName);
		$('#registerEventAccTime').val(moment(data.registerEventAccTime).format('YYYY/MM/DD HH:mm'));
		$('#gridName').val(data.gridName);
		$('#eventName').val(data.eventName);
		$('#registerEventSeriousLevelTitle').val(data.registerEventSeriousLevelTitle);
		$('#registerEventContent').val(data.registerEventContent);
		$('#registerEventMemo').val(data.registerEventMemo);
		
		$('#eventInfoDiv').show();
		
		var temp = createEventPoint(data);
		userLayer.add(temp);
		var temp_point_fick = createFlickerEventPoint(data);
		userLayer.add(temp_point_fick);
		map.centerAndZoom(temp.geometry, map.getLevel());
		// 防异步错误
		if(intervalflashTimeEvent){
			clearInterval(intervalflashTimeEvent);
			intervalflashTimeEvent=null;
		}
		// 单位数据刷新
		intervalflashTimeEvent = setInterval(function() {
			refreashFlickerEventPoint();
		}, 75);
		
		var url=window.rootPath+"/ui/userTrajectoryHistory/getEventUserListById/"+data.id+"/"+data.eventTaskUser;
		jQuery.ajax({
			url:encodeURI(url),
			cache:false,
			type : "get",
			dataType:"json",
			success:function(data){
				var users = data.users;
				$("#search").val('');
				initFollowPerson(users);
				initfollowState();
			}
		});
	}
};


function createFlickerEventPoint(data) {		
	var	symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 0, 255 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 0, 255, 1 ]) // 颜色和透明度
		);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
		var graphic = new esri.Graphic(myPoint);
		 graphic.symbol = symbol;
		 graphic.attributes = data;
//		 graphic.user = data;
		 graphic.pointType = showFlickerEventPointType;
	return graphic;
};
function refreashFlickerEventPoint() {
	var len =userLayer.graphics.length;
	var graphics = userLayer.graphics;
	for (var i = 0; i < len; i++) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerEventPointType ) {
			var symbol = graphic.symbol;
			if (symbol) {
				symbol.color.a -= 0.05;
				symbol.setSize(symbol.size + 8);
	
				if (symbol.color.a <= 0) {
					symbol.color.a = 1;
					symbol.setSize(1);
				}
				graphic.setSymbol(symbol);
			}
		}
	}
};


function createEventPoint(data){
	var longitude =  data.longitude;
	var latitude = data.latitude;
	if(longitude == 0 || latitude == 0){
		return null;
	}
	
	var icon = data.registerEventType.iconAddress;
	if (icon && icon!='') {
		icon = window.rootPath + '/'+icon;
	}else{
		icon = defaultEventTypeIcon;
	}
	icon = defaultEventTypeIcon;
	var symbol = new esri.symbol.PictureMarkerSymbol(icon, 40, 40).setOffset(0,0);
	var myPoint = {
			"geometry" : {
				"type" : "point",
				"x" : longitude,
				"y" : latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"attributes" : data,
			"symbol" : symbol
	};
	
	var graphic = new esri.Graphic(myPoint);
	graphic.symbol = symbol;
	graphic.attributes = data;
	
	return graphic;
}
// 创建图形
function createArea(data,num) {
	if (data.details) {
		var rings = [];

		var points = [];

		for (var i = 0; i < data.details.length; i++) {
			points.push([]);
		}

		for (var i = 0; i < data.details.length; i++) {
			var point = [];
			point.push(data.details[i].longtitude);
			point.push(data.details[i].latitude);

			points[data.details[i].longlatOrder] = point;
		}
		rings.push(points);

		var symbol = getPolygonDefaultSymbol();

		if(num==1){
			symbol=getPolygonHighSymbol();
		}
		
		var myPolygon = {
			"geometry" : {
				"rings" : rings,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" : {
				"color" : [ 0, 0, 0, 64 ],
				"outline" : {
					"outline" : [ 0, 0, 0, 255 ],
					"width" : 1,
					"type" : "esriSLS",
					"style" : "esriSFSSolid"
				}
			}
		};

		var graphic = new esri.Graphic(myPolygon);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.gridDetails = data.details;
		//gridLayer.add(graphic);
		return graphic;
	}
};
//创建图形
//function createLine(data,num,isfollow) {
//	if (data) {
//		var paths = [];
//
//		var points = [];
//
//		for (var i = 0; i < data.length; i++) {
//			points.push([]);
//		}
//
//		for (var i = 0; i < data.length; i++) {
//			var point = [];
//			point.push(data[i].longitude);
//			point.push(data[i].latitude);
//			points[i] = point;
//		}
//		paths.push(points);
//
//		var symbol = getLineDefaultSymbol();
//
//		if(num==1){
//			symbol=getLineHighSymbol();
//		}
//		
//		var myLine = {
//			"geometry" : {
//				"paths" : paths,
//				"type": "polyline",
//				"spatialReference" : {
//					"wkid" : 4326
//				}
//			},
//			"symbol" :symbol
//		};
//
//		var graphic = new esri.Graphic(myLine);
//		graphic.symbol = symbol;
//		graphic.attributes = data;
//		graphic.user=data[0].user;
//		graphic.isfollow=isfollow;
//		return graphic;
//	}
//};

function createLine(data,num,isfollow) {
	if (data) {
		var paths = [];
		
		var points = [];
		
		var userData = [];
		var graphic = null;
		for (var i = 0; i < data.length; i++) {
			if(points.length >0 && data[i].pointIndex == 0){
				paths.push(points);
				graphic = setLineToMap(userData,paths,isfollow);
				paths = [];
				points = [];
				userData = [];
			}
			var point = [];
			point.push(data[i].longitude);
			point.push(data[i].latitude);
			points.push(point);
			userData.push(data[i]);
		}
		paths.push(points);
		graphic = setLineToMap(userData,paths,isfollow);
		
		return graphic;
	}
};

function setLineToMap(data,paths,isfollow){
	
	var symbol = getLineDefaultSymbol();
	
	var myLine = {
		"geometry" : {
			"paths" : paths,
			"type": "polyline",
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"symbol" :symbol
	};
	
	var graphic = new esri.Graphic(myLine);
	graphic.symbol = symbol;
	graphic.attributes = data;
	graphic.user=data[0].user;
	graphic.isfollow=isfollow;
	
	userLayer.add(graphic);
	return graphic;
}
function createPoint(data, symbolurl,width,height) {
	var symbol = new esri.symbol.PictureMarkerSymbol({
		"url" : symbolurl, // 图标路径
		"width" : width, // 图标的宽度
		"height" : height
	// 图标的高度
	});

	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	/*
	 * , "infoTemplate": { "title": "sssss", "content": "latude:${Field}" }
	 */
	};
	var geometry = {
		"type" : "point",
		"x" : data.longitude,
		"y" : data.latitude,
		"spatialReference" : {
			"wkid" : 4326
		}
	};

	var graphic = new esri.Graphic(myPoint);
	graphic.symbol = symbol;
	graphic.attributes = data;
	// map.graphics.add(graphic);
	return graphic;
}
// 投影转换完成后调用方法
function MeasureGeometry(geometry) {
	require(
			[ "esri/tasks/AreasAndLengthsParameters",
					"esri/tasks/LengthsParameters" ],
			function(AreasAndLengthsParameters, LengthsParameters) {
				// 如果为线类型就进行lengths距离测算
				if (geometry.type == "polyline") {
					var lengthParams = new esri.tasks.LengthsParameters();
					lengthParams.polylines = [ geometry ];
					lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					lengthParams.geodesic = true;
					lengthParams.polylines[0].spatialReference = new esri.SpatialReference(
							4326);
					gsvc.lengths(lengthParams);
					dojo.connect(gsvc, "onLengthsComplete", outputDistance);
				}
				// 如果为面类型需要先进行simplify操作在进行面积测算
				else if (geometry.type == "polygon") {
					var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
					areasAndLengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
					areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_METERS;
					this.outSR = new esri.SpatialReference({
						wkid : 102113
					});
					gsvc
							.project(
									[ geometry ],
									this.outSR,
									function(geometry) {
										gsvc
												.simplify(
														geometry,
														function(
																simplifiedGeometries) {
															areasAndLengthParams.polygons = simplifiedGeometries;
															areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(
																	102113);
															gsvc
																	.areasAndLengths(areasAndLengthParams);
														});
									});
					dojo.connect(gsvc, "onAreasAndLengthsComplete",
							outputAreaAndLength);
				}
			});
};
// 显示测量面积
function outputAreaAndLength(result) {
	var textSymbol = new esri.symbol.TextSymbol("测量面积:"
			+ result.areas[0].toFixed(3) + "平方米");
	textSymbol.setFont({ // autocast as new Font()
		size : 20,
		family : "sans-serif",
		weight : "bolder"
	});
	textSymbol.setColor("white");
	text_graphic.setSymbol(textSymbol);

	console.log(result.areas[0].toFixed(3) + "平方米");
};
// 显示测量距离
function outputDistance(result) {
	var textSymbol = new esri.symbol.TextSymbol("测量长度:"+result.lengths[0].toFixed(3) + "米");
	textSymbol.setFont({ // autocast as new Font()
		size : 20,
		family : "sans-serif",
		weight : "bolder"
	});
	textSymbol.setColor("red");
	text_graphic.setSymbol(textSymbol);
	console.log(result.lengths[0].toFixed(3) + "米");
}

jQuery(document).ready(function () {
	$(window).resize(function(){
		var rightHeight=$("#left").height()-$("#footer").height()-$("#header").height();
		
		$("#map").height(rightHeight);
		$("#map").css({"height":+$("#right").height()+"px"}); 
	});
	getInfo();
});
	
function getInfo(){
	 var url=window.rootPath+"/ui/index/getConfigData";
     jQuery.ajax({
         url:encodeURI(url),
         cache:false,
         type : "get",
         dataType:"json",
         success:function(data){         
			//部门信息
			var depts=data.depts;
			var deptHtml='';
			if(data.depts.length>0){
				deptHtml += ' <li class="list_li oneDept one_li" dataId="all"><p>'+ "所有人员" +'</p></li>';
			}
			for(var i=0;i<depts.length;i++){
				if(depts[i].isParent > 0){
					deptHtml += '<dt class="list_dt deptdt" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
					deptHtml	 += '<dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
	    	 		}else{
	    	 			deptHtml += ' <li class="list_li oneDept one_li" dataId="'+depts[i].id+'"><p>'+ depts[i].groupName +'</p></li>';
	    	 		}
			}
			jQuery('#dept').empty();
			jQuery('#dept').append(deptHtml);
         }
     })
}
	
$("body").on("click",'.deptdt',function () {
	var clickObj =  $(this);
	var id = clickObj.attr('dataId');
	var url=window.rootPath+"/ui/index/getDeptNext/"+id;
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "get",
		dataType:"json",
		success:function(data){
			var depts = data.depts;
    	 		var deptHtml = '<ul>';
        	 	for(var i=0;i<depts.length;i++){
        	 		if(depts[i].isParent > 0){
        	 			deptHtml += ' <li class="list_li" dataId="'+depts[i].id+'">';
        	 			deptHtml += '<dt class="list_dt deptdt" dataId="'+depts[i].id+'"><span class="_after"></span><p>'+ depts[i].groupName +'</p><i class="list_dt_icon"></i></dt>';
        	 			deptHtml	 += ' <dd class="list_dd" id="dd'+depts[i].id+'"></dd>';
        	 			deptHtml	 += '</li>';
        	 			
        	 		}else{
        	 			deptHtml += ' <li class="list_li oneDept one_li" dataId="'+depts[i].id+'"><p>'+ depts[i].groupName +'</p></li>';
        	 		}
        	 	}
        	 	deptHtml += '</ul>';
    	 		jQuery('#dd'+id).empty();
    	 		jQuery('#dd'+id).append(deptHtml);
    	 		setSiblings(clickObj);
		}
	});
	
})


function initfollowState(){
	for(var i=0;i<userLayer.graphics.length;i++){
			if(userLayer.graphics[i].geometry.type=="polyline"){
				if(userLayer.graphics[i].isfollow=="0"){
					userLayer.graphics[i].hide();
				}		
		}
	}	
};

function initFollowPerson(users){
	if(!users){
		return;
	}
	var isfollow="1";
	var list=[];
    var currentUser='';
    var icon = window.rootPath + '/img/defaultTipstaff.png';
	for(var i=0;i<users.length;i++){
		if(currentUser!=users[i].user.id&&list.length>0){
			var temp=createLine(list,0,isfollow);
			userLayer.add(temp);
			var temp_point_fick=createFlickerPoint({
				"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
			    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
			});
			temp_point_fick.user=temp.user;
			temp_point_fick.isfollow=isfollow;
			userLayer.add(temp_point_fick);
			var temp_point = createPoint({
				"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
			    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
			}, icon,20,20);
			temp_point.user =temp.user;
			temp_point.isfollow=isfollow;
			userLayer.add(temp_point);
			var line_des=addLineDes(users[i-1]);
			line_des.user =temp.user;
			line_des.isfollow=isfollow;
			userLayer.add(line_des);
			list=[];												
		}
		currentUser=users[i].user.id;
		list.push(users[i]);					
	}
	if(list.length>0){
		var temp=createLine(list,0,isfollow);
//		userLayer.add(temp);
		var temp_point_fick = createFlickerPoint({
			"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
		    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
		});
		temp_point_fick.user=temp.user;
		temp_point_fick.isfollow=isfollow;
		userLayer.add(temp_point_fick);
		var temp_point = createPoint({
			"longitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][0],
		    "latitude":temp.geometry.paths[0][temp.geometry.paths[0].length-1][1]
		}, icon,20,20);
		temp_point.user =temp.user;
		temp_point.isfollow =isfollow;
		userLayer.add(temp_point);
		var line_des=addLineDes(users[users.length-1]);
		line_des.user=temp.user;
		line_des.isfollow=isfollow;
		userLayer.add(line_des);
		list=[];
		map.centerAndZoom(temp.geometry.paths[0][temp.geometry.paths[0].length-1], map.getLevel());
		// 防异步错误
		if(intervalflashTime){
			clearInterval(intervalflashTime);
			intervalflashTime=null;
		}
		// 单位数据刷新
		intervalflashTime = setInterval(function() {
			refreashFlickerPoint();
		}, 75);
	}
};

function createFlickerPoint(data) {		
	var	symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 0, 255, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 0, 255, 0, 1 ]) // 颜色和透明度
		);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
		var graphic = new esri.Graphic(myPoint);
		 graphic.symbol = symbol;
		 graphic.attributes = data;
		 graphic.user = data;
		 graphic.pointType = showFlickerPointTyp
	return graphic;
};

function refreashFlickerPoint() {
	var len =userLayer.graphics.length;
	var graphics = userLayer.graphics;
	for (var i = 0; i < len; i++) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerPointTyp ) {
			var symbol = graphic.symbol;
			if (symbol) {
				symbol.color.a -= 0.05;
				symbol.setSize(symbol.size + 8);

				if (symbol.color.a <= 0) {
					symbol.color.a = 1;
					symbol.setSize(1);
				}
				graphic.setSymbol(symbol);
			}
		}
	}
};

function addLineDes(data){
	var textSymbol = new esri.symbol.TextSymbol("人员:"+data.user.name);
	var point = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		}
	};
	var text_graphic = new esri.Graphic(point);
	text_graphic.setSymbol(textSymbol);
	text_graphic.attributes=data;
	return text_graphic;
};


$("body").on("click",'.oneDept',function () {
	$('.listdt').slideUp();
	var id = $(this).attr('dataId');
	showdeptUserDetail(id);
});

function setSiblings(obj) {
	$('.list_dd').stop();
	obj.siblings("dt").removeAttr("id");
	if(obj.attr("id")=="open"){
		obj.removeAttr("id").siblings("dd").slideUp();
	}else{
		obj.attr("id","open").next().slideDown().siblings("dd").slideUp();
	}
};

$("body").on("click",'#drawpolyline',function () {
	map.graphics.clear();
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	toolbar.activate(drawHandler.POLYLINE);
	$('body').css('cursor', 'crosshair');
	map.setMapCursor('crosshair');
	$('.listdt').slideUp();
});
$("body").on("click",'#exchangeTwoD',function () {
	$('.listdt').slideUp();
	if($("#twoDState").html()=="2.5D隐藏"){
		dynamic.hide();
		$("#twoDState").html("2.5D显示");
	}else{
		dynamic.show();
		$("#twoDState").html("2.5D隐藏");
	}
});

$("body").on("click",'#drawpolygon',function () {
	map.graphics.clear();
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	toolbar.activate(drawHandler.POLYGON);
	$('body').css('cursor', 'crosshair');
	map.setMapCursor('crosshair');
	$('.listdt').slideUp();
});

$("body").on("click",'#canceldraw',function () {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$('body').css('cursor', 'default');
	map.setMapCursor('default');
	$('.listdt').slideUp();
});

$("body").on("click",'#cleardraw',function () {
	map.graphics.clear();
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$('body').css('cursor', 'default');
	map.setMapCursor('default');
	$('.listdt').slideUp();
});

//周期切换
jQuery('#cyc').on('change',function(){
	var cyc = $(this).val();
	var cycDate = $('.cycDate');
	if(cyc == 'custom'){
		$('#userInfoDiv').height(200);
		cycDate.show();
	}else{
		$('#userInfoDiv').height(50);
		cycDate.hide();
		getUserToMapIds2();
	}
})

jQuery('.cycBtn').on("click",function(){
	var beginDate = $('#beginDate').val();
	var endDate = $('#endDate').val();
	if(beginDate == '' || endDate == ''){
		alert("请选择周期时间");
		return;
	}
	getUserToMapIds2();
});
	
$(window).unload(function(){  
	clearLayer();
}); 